/**
 * All rights Reserved, Designed By Android_Robot
 *
 * @Title: WebActivity.java
 * @Package com.jiyi.activity
 * @Description: TODO(用一句话描述该文件做什么)
 * @author: HYM
 * @date: 2017-7-11 下午3:03:10
 * @version V1.0
 */
package com.jiyi.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.swift.R;
import com.swift.base.ActivityBase;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.PermissionUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.utils.DialogTool;
import com.swift.utils.SerializableMap;
import com.swift.utils.WebViewBundle;
import com.swift.widget.CommonWebView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Map;

import okhttp3.Call;

import static com.swift.maintenance.base.AppConfig.ROOT_PATH;

public class WebActivity extends ActivityBase {

    RelativeLayout top;
    TextView tvBack;
    TextView tvTitle;
    TextView tvSearch;
    CommonWebView webView;

    String title = "";
    String rightClickTitle = "";
    int mWebRightClickCallBack;
    String url = "";
    Boolean canPhoto = false;
    Boolean isHideTitle = false;
    Map params;
    Dialog dialog;
    String fileName,fileAddr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        init();
    }

    @Override
    protected void onDestroy() {
        hideDialog(dialog);
        super.onDestroy();
    }

    private void init() {
        findView();
        title = getIntent().getStringExtra("title");
        rightClickTitle = getIntent().getStringExtra("rightClickTitle");
        mWebRightClickCallBack = getIntent().getIntExtra("WebRightClickCallBack", -1);
        url = getIntent().getStringExtra("url");
        isHideTitle = getIntent().getBooleanExtra("isHideTitle", false);
        if (isHideTitle) {
            top.setVisibility(View.GONE);
        }

        canPhoto = getIntent().getBooleanExtra("canPhoto", false);

        Bundle bundle = getIntent().getExtras();
        StringBuilder keyBuilder = new StringBuilder();
        SerializableMap serializableKeyMap = (SerializableMap) bundle
                .get(WebViewBundle.KEY);
        if (null != serializableKeyMap) {
            params = serializableKeyMap.getMap();
            Log.e(" fff   ",params.toString());
        }

        /*** 此处无需回调处理的js inteface */
        SerializableMap serializableToastMap = (SerializableMap) bundle
                .get(WebViewBundle.JS_INTEFACE);
        if (null != serializableToastMap) {
            // 需要监听的js接口对象
            Map<String, Object> map = serializableToastMap.getMap();
            webView.setMap(map);
            webView.setJsInteface();
        }

        /*** 此处需回调处理的js inteface */
        if (canPhoto) {
            // 可以使用拍照功能
            // webView.addJavascriptInterface(new
            // PhotoScriptInterface(this),"photo");
        }

        // 标题
        tvBack.setText("");
        tvTitle.setText(title);
        if (TextUtils.isEmpty(rightClickTitle)) {
            tvSearch.setVisibility(View.GONE);
        } else {
            tvSearch.setVisibility(View.VISIBLE);
            tvSearch.setText(rightClickTitle);
            tvSearch.setCompoundDrawables(null, null, null, null);
            if (mWebRightClickCallBack >= 0) {
                tvSearch.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        doTask(WebActivity.this, params);
                    }
                });
            }
        }

        webView.setWebViewClient(new WebChromeClientApp());
        webView.loadUrl(url);

        dialog = showDialog(dialog);
    }

    void findView() {
        top = (RelativeLayout) findViewById(R.id.top);
        tvBack = (TextView) findViewById(R.id.tvBack);
        tvBack.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvSearch = (TextView) findViewById(R.id.tvSearch);
        webView = (CommonWebView) findViewById(R.id.webView);
    }


    private class WebChromeClientApp extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (url.contains("/Wap/Maintenance/index.html") ||
                    url.contains("Wap/User/user_info.html") ||
                    url.contains("Home/Index/index.html") ||
                    url.contains("Owner/Index/index.html")
                    ) {
                finish();
            } else {
                super.onPageStarted(view, url, favicon);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            hideDialog(dialog);
        }
    }


    public static class RightClickEvent {
        public static final int downLoadDataInput = 1;
    }

    private void doTask(Context context, Map params) {
        dialog = showDialog(dialog);
        VolleyRequest.StringRequestPost(context, params.get("postUrl").toString(), "",
                params, new StringInterface(this) {

                    @Override
                    public void stringSuccess(String result) {
                        switch (mWebRightClickCallBack) {
                            case RightClickEvent.downLoadDataInput:
                                //高层评估报表下载
                                try {
                                    JSONObject obj = new JSONObject(result);
                                    String status = obj.getString("status");
                                    String info = obj.getString("info");
                                    if (status.equals("200")) {
                                        String data = obj.getString("data");
                                        JSONObject dataObj = new JSONObject(data);
                                        fileName = dataObj.getString("fileName");
                                        fileAddr = dataObj.getString("fileAddr");
                                        if (TextUtils.isEmpty(fileName) || TextUtils.isEmpty(fileAddr))
                                        {
                                            ToastUtil.getInstances().showMsg("请求的文件不存在");
                                            return;
                                        }

                                        if (PermissionUtil.checkPermission(WebActivity.this,PermissionUtil.WRITE))
                                        {
//                                            downLoad(fileAddr, fileName);
                                            new Handler().postDelayed(new Runnable() {
                                                @Override
                                                public void run() {
//                                                    downloadFile2(fileAddr, fileName);
                                                    downloadPDF(fileAddr, fileName);
                                                }
                                            },3500);
                                        }

                                    } else if (status.equals("404")
                                            && info.contains("尚未登录")) {
                                        ToastUtil.getInstances().showMsg(
                                                "尚未登录或该用户在其他地方登录，请重新登录！");
                                        // 清除环信登录
                                        UserHelp.getInstance().clearUser(
                                                AppBase.Context, true);
                                        return;
                                    } else {
                                        ToastUtil.getInstances().showMsg(info);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                } finally {
                                    DialogTool.hideDialog(dialog);
                                }

                                break;

                        }
                    }

                    @Override
                    public void stringError(VolleyError error) {
                        hideDialog(dialog);
                        ToastUtil.getInstances().showMsg(
                                com.swift.maintenance.R.string.err_http_response);
                    }
                });
    }

    String root = Environment.getExternalStoragePublicDirectory("").getPath();
    String downloadSavePath = root+"/jiyi/doc/";
    void downloadPDF(String url, final String fileName) {

        OkGo.<File>get(url)
                .tag("")
                .execute(new FileCallback(downloadSavePath, fileName) {
                    @Override
                    public void onSuccess(Response<File> response) {

                        MediaScannerConnection.scanFile(WebActivity.this, new String[]{root}, new String[]{"application/octet-stream"}, new MediaScannerConnection.OnScanCompletedListener() {
                            @Override
                            public void onScanCompleted(final String path, final Uri uri) {
                                //your file has been scanned!
                            }
                        });
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Uri uri = Uri.fromFile(new File(root));
                                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
                                WebActivity.this.sendBroadcast(intent);
                            }
                        },1000);


                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                File file = new File(downloadSavePath+fileName);
                                file.renameTo(new File(downloadSavePath+fileName));
toast("下载成功");
                            }
                        },2000);


                    }


                    @Override
                    public void uploadProgress(Progress progress) {
                        super.uploadProgress(progress);

                        com.orhanobut.logger.Logger.d("uploadProgress:" + progress.fraction);
                    }

                    @Override
                    public void downloadProgress(Progress progress) {
                        super.downloadProgress(progress);

//                        com.orhanobut.logger.Logger.d("downloadProgress:" +progress.fraction);


                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });

    }

    public void downloadFile1(String url, final String filename) {

            OkGo.<File>get(url)
                    .tag("")
                    .execute(new FileCallback(AppConfig.DIR_DOC,filename) {
                        @Override
                        public void onSuccess(Response<File> response) {

//                            toast("下载成功");


                            MediaScannerConnection.scanFile(WebActivity.this, new String[]{ROOT_PATH}, new String[]{"application/octet-stream"}, new MediaScannerConnection.OnScanCompletedListener() {
                                @Override
                                public void onScanCompleted(final String path, final Uri uri) {
                                    //your file has been scanned!
                                }
                            });


                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Uri uri = Uri.fromFile(new File(ROOT_PATH));
                                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
                                    WebActivity.this.sendBroadcast(intent);

                                }
                            },1000);


                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    File file = new File(AppConfig.DIR_DOC+filename);
                                    file.renameTo(new File(AppConfig.DIR_DOC+filename));
                                }
                            },2000);
                        }


                        @Override
                        public void uploadProgress(Progress progress) {
                            super.uploadProgress(progress);

                            com.orhanobut.logger.Logger.d("uploadProgress:" +progress.fraction);

                        }

                        @Override
                        public void downloadProgress(Progress progress) {
                            super.downloadProgress(progress);

//                        com.orhanobut.logger.Logger.d("downloadProgress:" +progress.fraction);



                        }

                        @Override
                        public void onError(Response<File> response) {
                            super.onError(response);

                            Logger.d("出错了: " + response.message().toString());
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                        }
                    });

    }

    public void downloadFile2(String url, final String filename) {

        OkGo.<File>get(url)
                .tag("")
                .execute(new FileCallback(AppConfig.DIR_DOC,filename) {
                    @Override
                    public void onSuccess(Response<File> response) {

                            toast("下载成功");


                        MediaScannerConnection.scanFile(WebActivity.this, new String[]{ROOT_PATH}, new String[]{"application/octet-stream"}, new MediaScannerConnection.OnScanCompletedListener() {
                            @Override
                            public void onScanCompleted(final String path, final Uri uri) {
                                //your file has been scanned!
                            }
                        });


                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Uri uri = Uri.fromFile(new File(ROOT_PATH));
                                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
                                WebActivity.this.sendBroadcast(intent);

                            }
                        },1000);


                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                File file = new File(AppConfig.DIR_DOC+filename);
                                file.renameTo(new File(AppConfig.DIR_DOC+filename));
                            }
                        },2000);
                    }


                    @Override
                    public void uploadProgress(Progress progress) {
                        super.uploadProgress(progress);

                        com.orhanobut.logger.Logger.d("uploadProgress:" +progress.fraction);

                    }

                    @Override
                    public void downloadProgress(Progress progress) {
                        super.downloadProgress(progress);

//                        com.orhanobut.logger.Logger.d("downloadProgress:" +progress.fraction);



                    }

                    @Override
                    public void onError(Response<File> response) {
                        super.onError(response);

                        Logger.d("出错了: " + response.message().toString());
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });

    }

    void downLoad(String url, final String fileName) {
        Log.e("url     ",url);
        Log.e("fileName     ",fileName);

        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(
                        new FileCallBack(AppConfig.DIR_DOC, fileName) {

                            @Override
                            public void onError(Call arg0, Exception e, int arg2) {
                                Log.e(" sdfdsfdsf ",
                                        "onError :" + e.getMessage());
                            }

                            @Override
                            public void onResponse(File file, int arg1) {
                                Log.e(" sdfdsfdsf ",
                                        "onResponse :" + file.getAbsolutePath());
                                ToastUtil.getInstances().showMsg(
                                        "已下载到sdcard下的" + fileName);

                            }
                        });
    }

    final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE=1;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                downLoad(fileAddr, fileName);
                downloadFile1(fileAddr, fileName);
            } else {
                ToastUtil.getInstances().showMsg("无保存文件权限");
            }
        }
    }
}
